'use strict';

var _ = require('lodash');
var Document = require('./document.model');
var Project = require('../project/project.model');
var Report = require('../report/report.model');
var Timeline = require('../timeline/timeline.model');
var UploadPath = __dirname+'/../../../public';
var fs = require('fs');

// Get list of documents
exports.index = function(req, res) {
  Document.find().sort({created_at: -1}).exec(function (err, documents) {
    if(err) { return handleError(res, err); }
    return res.json(200, documents);
  });
};

// Get a single document
exports.show = function(req, res) {
  Document.findById(req.params.id).exec(function (err, document) {
    if(err) { return handleError(res, err); }
    if(!document) { return res.send(404); }
    return res.json(document);
  });
};

// Creates a new document in the DB.
exports.create = function(req, res) {
  console.log(req);
  var now = new Date();
  //return res.json(201, req.files);//你可能需要修改相关的newPath到你自己的地址
  var filePath = req.files.file.path;
  var upload_dir = UploadPath+'/assets/upload/' +req.body.projectId;
  fs.readdir(upload_dir, function(err, files){
    if(err){
      fs.mkdirSync(upload_dir, '0777');
      return console.log('不存在此目录');
    }
  });
  var uploadPath = "/assets/upload/" +req.body.projectId+'/'+ req.files.file.name;
  var newPath = UploadPath + uploadPath;
  console.log(newPath);

  //把图片从临时文件夹复制到目的文件夹，当然最好删除临时文件
  fs.readFile(filePath, function (err, data) {
    if (err) {
      res.send(err);
      console.log('读取失败！');
      return;
    }

    fs.writeFile(newPath, data, function (err) {
      if (!err) {
        var newDocument = {
          _user: JSON.parse(req.body.user),
          _project: req.body.projectId,
          title: req.files.file.name,
          file_name: req.files.file.name,
          file_path: uploadPath,
          file_size: req.files.file.size/1024+'KB',
          file_type: req.files.file.type
        };
        var newTimeline = {
          _user: newDocument._user._id,
          type: 'document',
          message: newDocument.title
        };
        Timeline.create(newTimeline, function(err, timeline) {
          if(err) { return handleError(res, err); }
          console.log(timeline);
        });
        Document.create(newDocument, function(err, document) {
          if(err) { return handleError(res, err); }
          Project.findByIdAndUpdate(
            req.body.projectId,
            {$push: {files: document._id}},
            {},
            function(err, model) {
              console.log(err);
            }
          );
          return res.json(201, document);
        });
      } else {
        res.send(err);
        console.log('上传失败！');
      }
    });
  });
  //Document.create(req.body, function(err, document) {
  //  if(err) { return handleError(res, err); }
  //  return res.json(201, document);
  //});
};

// Creates a new document in the DB.
exports.report = function(req, res) {
  console.log(req.files);
  console.log(req.body);
  var now = new Date();
  //return res.json(201, req.files);//你可能需要修改相关的newPath到你自己的地址
  var filePath = req.files.file.path;
  var upload_dir = UploadPath+'/assets/upload/' +req.body.reportId;
  fs.readdir(upload_dir, function(err, files){
    if(err){
      fs.mkdirSync(upload_dir, '0777');
      return console.log('不存在此目录');
    }
  });
  var uploadPath = "/assets/upload/" +req.body.reportId+'/'+ req.files.file.name;
  var newPath = UploadPath + uploadPath;
  console.log(newPath);

  //把图片从临时文件夹复制到目的文件夹，当然最好删除临时文件
  fs.readFile(filePath, function (err, data) {
    if (err) {
      res.send(err);
      console.log('读取失败！');
      return;
    }

    fs.writeFile(newPath, data, function (err) {
      if (!err) {
        var newDocument = {
          _user: JSON.parse(req.body.user),
          title: req.files.file.name,
          file_name: req.files.file.name,
          file_path: uploadPath,
          file_size: req.files.file.size/1024+'KB',
          file_type: req.files.file.type
        };
        var newTimeline = {
          _user: newDocument._user._id,
          type: 'document',
          message: newDocument.title
        };
        Timeline.create(newTimeline, function(err, timeline) {
          if(err) { return handleError(res, err); }
          console.log(timeline);
        });
        Document.create(newDocument, function(err, document) {
          if(err) { return handleError(res, err); }
          Report.findByIdAndUpdate(
            req.body.reportId,
            {$push: {files: document._id}},
            {},
            function(err, model) {
              console.log(err);
            }
          );
          return res.json(201, document);
        });
      } else {
        res.send(err);
        console.log('上传失败！');
      }
    });
  });
  //Document.create(req.body, function(err, document) {
  //  if(err) { return handleError(res, err); }
  //  return res.json(201, document);
  //});
};

// Updates an existing document in the DB.
exports.update = function(req, res) {
  if(req.body._id) { delete req.body._id; }
  Document.findById(req.params.id, function (err, document) {
    if (err) { return handleError(res, err); }
    if(!document) { return res.send(404); }
    var updated = _.merge(document, req.body);
    updated.save(function (err) {
      if (err) { return handleError(res, err); }
      return res.json(200, document);
    });
  });
};

// Deletes a document from the DB.
exports.destroy = function(req, res) {
  Document.findById(req.params.id, function (err, document) {
    if(err) { return handleError(res, err); }
    if(!document) { return res.send(404); }
    fs.unlink(UploadPath+document.file_path);
    Project.findByIdAndUpdate(
      document._project,
      {$pull: {files: document._id}},
      {},
      function(err, model) {
        console.log(err);
      }
    );
    document.remove(function(err) {
      if(err) { return handleError(res, err); }
      return res.send(204);
    });
  });
};

function handleError(res, err) {
  return res.send(500, err);
}
